package com.midea.ai.air.ui.device.product.airconditioner;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.midea.ai.air.R;
import com.midea.ai.air.common.BaseFragment;
import com.midea.ai.air.ui.device.product.DeviceMainActivity;
import com.midea.ai.air.ui.device.product.airconditioner.view.CircleView;
import com.midea.ai.air.ui.device.product.utils.MetricsUtils;
import com.midea.ai.air.ui.device.product.view.FuncItemView;
import com.midea.ai.air.ui.device.product.view.TitleBarView;
import com.midea.ai.air.ui.home.HomeAirSetting;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 空调主界面
 *
 * Created by tanchuo on 16/3/21.
 */
public class AircBaseFragment extends BaseFragment implements GestureDetector.OnGestureListener
{
    private View root;
    private TitleBarView titleBarView;
    private LinearLayout funcView;   //功能按钮layout
    private LinearLayout funcView01,funcView02,funcView03,funcView04;  //功能按钮子layout
    private CircleView circleView;    //温度控制圆盘
    private ImageView modeImage;    //当前模式对应的图片
    private Button addTempBtn,minusTempBtn; //升高和降低温度

    private float x,y;
    private int bigHeight = 800;
    private int smallHeight = 200;
    private int missHeight = 800;

    private int funcViewWidth;  //功能view的高度

    private int funcNum = 10;  //统计功能数的总数

    private float yUp, yDown, yMove, yChange, yMoveBase,yd;

    private Timer moveTimer;

    private int alpha = 225;

    private GestureDetector gestureDetector;
    private Activity activity;
    private DeviceMainActivity.MyOntouchListener listener;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        activity = getActivity();
        gestureDetector = new GestureDetector(activity, this);
        listener = new DeviceMainActivity.MyOntouchListener()
        {

            @Override
            public void onTouchEvent(MotionEvent event)
            {
                gestureDetector.onTouchEvent(event);
                if (event.getAction() == MotionEvent.ACTION_UP)
                {
                    Log.d("ontouchme", "---ACTION_UP");
                    yUp = event.getY();
                    doMoveAction(yUp, yDown);
                }
            }
        };
        ((DeviceMainActivity) activity).registerListener(listener);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        root = inflater.inflate(R.layout.fragment_airc_main,container,false);
        initTitleBar(root);
        initData();
        initFuncData();
        initFuncView(root);
        initCircle(root);
        initView();

        return root;
    }

    private void initView()
    {

        modeImage = (ImageView)root.findViewById(R.id.airc_main_mode_image);
        addTempBtn = (Button)root.findViewById(R.id.airc_add_temp_btn);
        minusTempBtn = (Button)root.findViewById(R.id.airc_minus_temp_btn);

        addTempBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //升高温度

            }
        });

        minusTempBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //降低温度

            }
        });

    }

    private void initData()
    {
        funcViewWidth = MetricsUtils.Dp2Px(getActivity(),100);

    }

    private void initCircle(View root)
    {
        circleView = (CircleView)root.findViewById(R.id.airc_main_circle);
        circleView.setOnTouchListener(onTouchListener);
    }

    View.OnTouchListener onTouchListener = new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            Log.d("CircleView", "event.getX() = " + event.getAction()
                    + ",event.getY() = " + event.getY());

            x = event.getX();
            y = event.getY();

            float l = (float) Math.sqrt((x - circleView.getWidth() / 2.0)
                    * (x - circleView.getWidth() / 2.0)
                    + (y - circleView.getHeight() / 2.0)
                    * (y - circleView.getHeight() / 2.0));

            if (l < MetricsUtils.Dp2Px(getActivity(), 60)
                    || l > MetricsUtils.Dp2Px(getActivity(), 180))
            {
                return true;
            }

            if (funcViewWidth > smallHeight + 50)
            {
                return true;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {

            }

            if (event.getAction() == MotionEvent.ACTION_MOVE)
            {
                float radiu = (float) (((float) Math.atan2(
                        y - (circleView.getHeight() / 2),
                        x - (circleView.getWidth() / 2))
                        * (float) 180 / Math.PI) + 90);
                Log.d("radiu", "radiu = " + radiu);

                if (radiu > 150 && radiu < 210)
                {

                }
                else
                {
                    if (radiu >= -90 && radiu <= 150)
                    {
                        float west0 = 60 + 25 * radiu / 150;
//                        setHumi = (int) Math.round(west0 + 0.5)
//                                - (int) Math.round(west0 + 0.5) % 5;
//                        humiSet.setText(setHumi + "");
                    }
                    else if (radiu >= 210 && radiu <= 270)
                    {
                        float west0 = 35 + (radiu - 210) / 6;
//                        setHumi = (int) Math.round(west0)
//                                - (int) Math.round(west0) % 5;
//                        humiSet.setText(setHumi + "");
                    }

                    circleView.doAction(x, y, 50, 0);
                    // circleView.doAction(x, y, 40);
                }
            }

            if (event.getAction() == MotionEvent.ACTION_UP)
            {
                //功能动作
            }
            return true;
        }
    };

    private void initFuncData()
    {

    }

    private void initFuncView(View root)
    {
        funcView = (LinearLayout)root.findViewById(R.id.device_main_func_view);
        funcView01 = (LinearLayout)root.findViewById(R.id.device_main_func_layout1);
        funcView02 = (LinearLayout)root.findViewById(R.id.device_main_func_layout2);
        funcView03 = (LinearLayout)root.findViewById(R.id.device_main_func_layout3);
        funcView04 = (LinearLayout)root.findViewById(R.id.device_main_func_layout4);

        for (int i = 0; i < 4; i++)
        {
            FuncItemView mFuncItemView = new FuncItemView(getActivity());
            mFuncItemView.setText("定时");
            mFuncItemView.setBackGroundRes(R.drawable.air_home_advice_1);
            mFuncItemView.setOnCheckChangeListener(mOnClickListener);
            mFuncItemView.btn.setTag("定时");

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            layoutParams.gravity = Gravity.LEFT;
            funcView01.addView(mFuncItemView, layoutParams);
        }

        for (int i = 0; i < 4; i++)
        {
            FuncItemView mFuncItemView = new FuncItemView(getActivity());
            mFuncItemView.setText("定时");
            mFuncItemView.setBackGroundRes(R.drawable.air_home_advice_1);
            mFuncItemView.setOnCheckChangeListener(mOnClickListener);
            mFuncItemView.btn.setTag("定时");

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            layoutParams.gravity = Gravity.LEFT;
            funcView02.addView(mFuncItemView, layoutParams);
        }

        for (int i = 0; i < 4; i++)
        {
            FuncItemView mFuncItemView = new FuncItemView(getActivity());
            mFuncItemView.setText("定时");
            mFuncItemView.setBackGroundRes(R.drawable.air_home_advice_1);
            mFuncItemView.setOnCheckChangeListener(mOnClickListener);
            mFuncItemView.btn.setTag("定时");

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            layoutParams.gravity = Gravity.LEFT;
            funcView03.addView(mFuncItemView, layoutParams);
        }

        for (int i = 0; i < 4; i++)
        {
            FuncItemView mFuncItemView = new FuncItemView(getActivity());
            mFuncItemView.setText("定时");
            mFuncItemView.setBackGroundRes(R.drawable.air_home_advice_1);
            mFuncItemView.setOnCheckChangeListener(mOnClickListener);
            mFuncItemView.btn.setTag("定时");

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            layoutParams.gravity = Gravity.LEFT;
            funcView04.addView(mFuncItemView, layoutParams);
        }
    }

    View.OnClickListener mOnClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

        }
    };

    private void initTitleBar(View root)
    {
        titleBarView = (TitleBarView)root.findViewById(R.id.device_title_bar);
        titleBarView.setOnLeftButtonClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //退出当前页面
                getActivity().finish();
            }
        });

        titleBarView.setOnRightButtonClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //前往更多设置
                startActivity(new Intent(getActivity(), HomeAirSetting.class));
            }
        });
    }

    @Override
    public boolean onDown(MotionEvent e)
    {
        yDown = e.getY();
        yChange = yDown;
        yMoveBase = yDown;
        doMoveCancel();
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e)
    {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e)
    {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        doMoving(distanceY);

        if (e2.getAction() == MotionEvent.ACTION_UP)
        {
            Log.d("ontouchme", "---ACTION_UP");
        }

        return true;
    }

    @Override
    public void onLongPress(MotionEvent e)
    {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        return false;
    }

    protected void doMoveAction(float yUp2, float yDown2)
    {
        yd = yUp2 - yDown2;
        if (yd > 20 || yd < -20)
        {
            if (moveTimer == null)
            {
                moveTimer = new Timer();
                moveTimer.schedule(new MoveTask(), 0, 5);
            }
        }
        else
        {

        }
    }

    class MoveTask extends TimerTask
    {
        @Override
        public void run()
        {
            if (yd > 20)
            {
                handler.sendEmptyMessage(1);
            }
            else if (yd < -20)
            {
                handler.sendEmptyMessage(0);
            }
        }
    }

    Handler handler = new Handler()
    {
        @SuppressLint("NewApi")
        public void handleMessage(android.os.Message msg)
        {
            switch (msg.what)
            {
                case 0: // move up
                    funcViewWidth = funcViewWidth
                            + MetricsUtils.Dp2Px(getActivity(), 4);
                    if (funcViewWidth > bigHeight)
                    {
                        funcViewWidth = bigHeight;
                        addTempBtn.setVisibility(View.VISIBLE);
                        minusTempBtn.setVisibility(View.VISIBLE);
                        moveTimerCancel();
                    }
                    RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT, funcViewWidth);
                    mLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);
                    funcView.setLayoutParams(mLayoutParams);

                    if (funcViewWidth > missHeight)
                    {
                        alpha = 0;
                        //slideView.setImageResource(R.drawable.slide_d);
                    } else
                    {
                        alpha = (int) (((float) (missHeight - funcViewWidth) / ((float) (missHeight - smallHeight))) * (float) 225);
                        //slideView.setImageResource(R.drawable.slide);
                    }
                    circleView.setAlpha((float) alpha / 225);
                    modeImage.setImageAlpha(alpha);
                    break;
                case 1: // move down

                    funcViewWidth = funcViewWidth
                            - MetricsUtils.Dp2Px(getActivity(), 3);
                    if (funcViewWidth < smallHeight)
                    {
                        funcViewWidth = smallHeight;
                        addTempBtn.setVisibility(View.GONE);
                        minusTempBtn.setVisibility(View.GONE);
                        moveTimerCancel();
                    }
                    RelativeLayout.LayoutParams mLayoutParams2 = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT, funcViewWidth);
                    mLayoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);
                    funcView.setLayoutParams(mLayoutParams2);

                    if (funcViewWidth > missHeight)
                    {
                        alpha = 0;
                        //slideView.setImageResource(R.drawable.slide_d);
                    } else
                    {
                        alpha = (int) (((float) (missHeight - funcViewWidth) / ((float) (missHeight - smallHeight))) * (float) 225);
                        //slideView.setImageResource(R.drawable.slide);
                    }
                    circleView.setAlpha((float) alpha/225);
                    modeImage.setImageAlpha(alpha);
                    break;
            }
        }
    };

    protected void doMoveCancel()
    {
        moveTimerCancel();
    }

    private void moveTimerCancel()
    {
        if (moveTimer != null)
        {
            moveTimer.cancel();
            moveTimer = null;
        }
    }

    protected void doMoving(float move)
    {
        int distance = (int) (move);
        yChange = move;
        int width = funcViewWidth + distance;
        if (width < smallHeight || width > bigHeight)
        {
            return;
        }
        funcViewWidth = width;
        if (funcViewWidth > missHeight)
        {
            alpha = 0;
            //slideView.setImageResource(R.drawable.slide_d);
        }
        else
        {
            alpha = (int) (((float) (missHeight - funcViewWidth) / ((float) (missHeight - smallHeight))) * (float) 225);
            //slideView.setImageResource(R.drawable.slide);
        }
        circleView.setAlpha((float) alpha / 225);

        RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, funcViewWidth);
        mLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);
        funcView.setLayoutParams(mLayoutParams);

        addTempBtn.setVisibility(View.GONE);
        minusTempBtn.setVisibility(View.GONE);
    }

    @Override
    public void onDestroy()
    {
        moveTimerCancel();
        super.onDestroy();
    }
}
